package com.zhkj.txg.module.mine.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.module.mine.entity.CouponCenterResponse
import com.zhkj.txg.module.mine.entity.CouponGetResponse
import com.zhkj.txg.module.mine.entity.CouponListResponse
import com.zhkj.txg.module.mine.model.MineManager

class CouponViewModel(application: Application) : BaseViewModel(application) {
    private val mineManager = MineManager()
    val couponListLiveData = MutableLiveData<HttpResponse<CouponListResponse>>()
    val couponCenterListLiveData = MutableLiveData<HttpResponse<CouponCenterResponse>>()
    val getCouponLiveData = MutableLiveData<HttpResponse<CouponGetResponse>>()

    var useType: Int = 0
    var apiType: Int = 0
    var status: Int = 0

    private val numb = 20
    var page = 1
        private set

    fun couponList(restart: Boolean = false) {
        val listener = object : ViewModelSubscribeListener<CouponListResponse>(couponListLiveData) {
            override fun onSuccess(resp: CouponListResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val couponList = mineManager.couponList(
            AccountManager.getToken(), useType, apiType, status,
            page, numb, listener
        )
        dispose.add(couponList)
    }

    fun couponCenterList(restart: Boolean = false) {
        val listener =
            object : ViewModelSubscribeListener<CouponCenterResponse>(couponCenterListLiveData) {
                override fun onSuccess(resp: CouponCenterResponse) {
                    resp.hasMore = resp.data.size >= numb
                    resp.loadMore = page > 1
                    super.onSuccess(resp)
                    page += 1
                }
            }
        if (restart) page = 1
        val couponCenter =
            mineManager.couponCenter(AccountManager.getToken(), useType, page, numb, listener)
        dispose.add(couponCenter)
    }

    fun getCoupon(id: Long, uiPosition: Int) {
        val listener = object : ViewModelSubscribeListener<CouponGetResponse>(getCouponLiveData) {
            override fun onSuccess(resp: CouponGetResponse) {
                resp.uiPosition = uiPosition
                super.onSuccess(resp)
            }
        }
        val coupon = mineManager.getCoupon(AccountManager.getToken(), id, listener)
        dispose.add(coupon)
    }
}